package com.mocne.Common;

import java.sql.*;

public class SqlHandle {

    // JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/mocne_test";

    // 数据库的用户名与密码，需要根据自己的设置
    static final String USER = "mocne";
    static final String PASS = "a1111111";
    Connection conn = null;
    Statement stmt = null;
    ResultSet Irs;
    ResultSet Srs;

    public boolean testConnection() {

        try{
            // 注册 JDBC 驱动
            Class.forName("com.mysql.jdbc.Driver");

            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL,USER,PASS);
            return true;
        }catch(SQLException se){
            // 处理 JDBC 错误
            se.printStackTrace();
        }catch(Exception e){
            // 处理 Class.forName 错误
            e.printStackTrace();
        }finally{

        }
        System.out.println("Goodbye!");
        return false;
    }

    public void testInsert(String sqlInsert) throws SQLException {
        if (testConnection()) {
            //执行数据插入
            System.out.println(" 实例化Statement对...");
            stmt = conn.createStatement();
            ResultSet Irs = stmt.executeQuery(sqlInsert);
            System.out.println(Irs.toString());
            afterTest();
        }
    }

    public void testSelect(String sqlSelect) throws SQLException {
        if (testConnection()) {
            // 执行查询
            System.out.println(" 实例化Statement对...");
            stmt = conn.createStatement();
            ResultSet Srs = stmt.executeQuery(sqlSelect);

            // 展开结果集数据库
            while(Srs.next()){
                // 通过字段检索
                int id  = Srs.getInt("id");
                String name = Srs.getString("name");
                String address = Srs.getString("address");

                // 输出数据
                System.out.print("ID: " + id);
                System.out.print(", 名称: " + name);
                System.out.print(", 地址: " + address);
                System.out.print("\n");
            }
            afterTest();
        }
    }


    public void afterTest() throws SQLException {
        stmt.close();
        conn.close();
        // 关闭资源
        try{
            if(stmt!=null) stmt.close();
        }catch(SQLException se2){
        }// 什么都不做
        try{
            if(conn!=null) conn.close();
        }catch(SQLException se){
            se.printStackTrace();
        }

        // 完成后关闭
        Irs.close();
        Srs.close();
    }

}
